package org.smart4j.framework.helper;

import org.smart4j.framework.annotation.Inject;
import org.smart4j.framework.util.ArrayUtil;
import org.smart4j.framework.util.CollectionUtil;
import org.smart4j.framework.util.ReflectionUtil;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * 依赖注入助手类
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2017-12-15
 **/
public  final class IocHelper {

/*
* 通过BeanHelper 获取所有BeanMap（是一个类与对象的对应）然后遍历这个映射关系，分别取出Bean类与Bean实例，进而
* 通过反射获取类中所有的成员变量。继续遍历这些成员变量，在循环中判断当前成员比变量是否带有Inject注解，若带有该注解，则从
* BeanMap中根据Bean类取出Bean实例，最后通过ReflectionUtil.setField方法来修改当前成员变量的值
* */

    static{
        Map<Class<?>,Object> beanMap = BeanHelper.getBeanMap();
        if(CollectionUtil.isNotEmpty(beanMap)){
            for(Map.Entry<Class<?>,Object> beanEntry : beanMap.entrySet()){
                Class<?> beanClass = beanEntry.getKey();
                Object beanInstance = beanEntry.getValue();
                Field[] beanFields = beanClass.getDeclaredFields();
                if(ArrayUtil.isNotEmpty(beanFields)){
                   for(Field beanField:beanFields){
                       if(beanField.isAnnotationPresent(Inject.class)){
                           Class<?> beanFieldClass = beanField.getType();
                           Object beanFieldInstance = beanMap.get(beanFieldClass);
                           if(beanFieldInstance!=null){
                               ReflectionUtil.setField(beanInstance,beanField,beanFieldInstance);
                           }
                       }
                   }
                }
            }
        }
    }
}
